﻿using GBT.ParamEntity;
using GBT.SystemBusinessCore;
using GBT.SystemEnties;
using NLog;
using QueryDataLogic.Core;
using SqlSugar;
using System;
using System.Linq.Expressions;

namespace PersistenceDataLogic.Core
{
    public class OperationTakeFoodRecord
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        BasicInfo bi = new BasicInfo();
        DbContext<TakeFoodRecord> dbContext = null;
        SqlSugarClient db = null;
        OperationMeal operationMeal = new OperationMeal();

        public OperationTakeFoodRecord(string DBName)
        {
            dbContext = new DbContext<TakeFoodRecord>(DBName);
            db = dbContext.Db;
        }

        public OperationTakeFoodRecord()
        {

        }

        public bool IsTakeFoodRecord(TakeFoodRecord takeFoodRecord, DbContext<TakeFoodRecord> dbContext, Expression<Func<TakeFoodRecord, bool>> whereLam)
        {
            return dbContext.IsExists(whereLam);
        }

        public TakeFoodRecord AddOrModifyTakeFoodRecord(TakeFoodRecord takeFoodRecord, ref string msg)
        {
            string dbName = bi.GetDBName(takeFoodRecord.DistrictID);
            if (dbContext == null)
                dbContext = new DbContext<TakeFoodRecord>(dbName);
            var db = dbContext.Db;
            var versions = bi.GetVersions(takeFoodRecord.DistrictID);
            try
            {
                DateTime dateTime = DateTime.Now.Date;
                if (IsTakeFoodRecord(takeFoodRecord, dbContext, t => t.UUID == takeFoodRecord.UUID && t.CreationDate > dateTime))
                {
                    var userInfo = db.Queryable<MealUser>().Where(t => t.UserID == takeFoodRecord.UserID).First();
                    msg = userInfo.Name + " 已取餐";
                    return null;
                }
                db.Ado.BeginTran();
                if (takeFoodRecord.ID == 0)
                {
                    MealTime mealTime = db.Queryable<MealTime>().Where(t => SqlFunc.ToTime(t.startTime) <= SqlFunc.ToTime(SqlFunc.GetDate()) && SqlFunc.ToTime(t.endTime) >= SqlFunc.ToTime(SqlFunc.GetDate())).First();
                    if (mealTime != null)
                    {
                        takeFoodRecord.MealID = mealTime.MealId;
                        //版本号为 5-旗舰无报餐版本时 第一次扫码取员工价，第二次及以上扫码取家庭餐价，
                        //其他版本都是需要有报餐且第一次扫码取员工价，其他都取家庭餐价
                        if (versions.Number == "5")
                        {
                            //当天同一餐 第一次扫码 按补贴价 第二次扫码开始 都按 家属餐价
                            if (IsTakeFoodRecord(takeFoodRecord, dbContext, t => t.UserID == takeFoodRecord.UserID && t.MealID == takeFoodRecord.MealID && t.HallID == takeFoodRecord.HallID && t.DistrictID == takeFoodRecord.DistrictID && t.CreationDate > dateTime))
                            {
                                //第二次及以上扫码
                                takeFoodRecord.Price = (decimal)mealTime.FamilyPrice;
                            }
                            else
                            {
                                //第一次扫码
                                takeFoodRecord.Price = (decimal)mealTime.Price;
                            }
                        }
                        else
                        {
                            System_ReportMeals reportMeals = new System_ReportMeals();
                            reportMeals.hallID = takeFoodRecord.HallID;
                            reportMeals.userID = takeFoodRecord.UserID;
                            reportMeals.date = dateTime;
                            reportMeals.mealID = mealTime.MealId;
                            DbContext<ReportMeals> reportMealDb = new DbContext<ReportMeals>(dbName);
                            //判断是否有报餐，有报餐且第一次扫码则取员工价，否则取家庭餐价
                            if (operationMeal.IsMealReport(reportMeals, reportMealDb) && !IsTakeFoodRecord(takeFoodRecord, dbContext, t => t.UserID == takeFoodRecord.UserID && t.MealID == takeFoodRecord.MealID && t.HallID == takeFoodRecord.HallID && t.DistrictID == takeFoodRecord.DistrictID && t.CreationDate > dateTime))
                            {
                                takeFoodRecord.Price = (decimal)mealTime.Price;
                            }
                            else
                            {
                                takeFoodRecord.Price = (decimal)mealTime.FamilyPrice;
                            }
                        }
                        takeFoodRecord.Qty = 1;
                        takeFoodRecord.CreationDate = DateTime.Now;
                        takeFoodRecord = dbContext.InsertReturnEntity(takeFoodRecord);

                        //修改充值记录
                        var userStoredValue = db.Queryable<UserStoredValue>().Where(t => t.UserID == takeFoodRecord.UserID).First();
                        if (userStoredValue == null)
                        {
                            var userInfo = db.Queryable<MealUser>().Where(t => t.UserID == takeFoodRecord.UserID).First();
                            msg = userInfo.Name + " 余额不足";
                            db.Ado.RollbackTran();
                            return null;
                        }
                        else
                        {
                            userStoredValue.Value = userStoredValue.Value - takeFoodRecord.Qty * takeFoodRecord.Price;
                            if (userStoredValue.Value < 0)
                            {
                                var userInfo = db.Queryable<MealUser>().Where(t => t.UserID == takeFoodRecord.UserID).First();
                                msg = userInfo.Name + " 余额不足";
                                db.Ado.RollbackTran();
                                return null;
                            }
                            //新增消费记录
                            UserXpenseTracker userXpenseTracker = new UserXpenseTracker();
                            userXpenseTracker.UserID = takeFoodRecord.UserID;
                            userXpenseTracker.Value = 0 - takeFoodRecord.Qty * takeFoodRecord.Price;
                            userXpenseTracker.HallID = takeFoodRecord.HallID;
                            userXpenseTracker.UserValue = userStoredValue.Value;
                            userXpenseTracker.Remark = "取餐消费";
                            userXpenseTracker.CreationDate = DateTime.Now;
                            db.Insertable(userXpenseTracker).ExecuteCommand();
                            //修改账户余额
                            db.Updateable(userStoredValue).ExecuteCommand();
                        }

                        msg = "取餐成功";
                    }
                    else
                    {
                        msg = "无效餐时";
                        db.Ado.RollbackTran();
                        return null;
                    }
                }
                else
                {
                    takeFoodRecord = dbContext.UpdateReturnEntity(takeFoodRecord);
                }
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                Console.WriteLine(ex);
                logger.Error(ex);
                msg = "请刷新二维码后，重新扫描";
            }
            return takeFoodRecord;
        }

        public bool DeleteTakeFoodRecord(System_TakeFoodRecord takeFoodRecord)
        {
            bool start = true;
            string dbName = bi.GetDBName(takeFoodRecord.DistrictID);
            dbContext = new DbContext<TakeFoodRecord>(dbName);
            var db = dbContext.Db;
            try
            {
                db.Ado.BeginTran();
                //修改账户余额
                var userStoredValue = db.Queryable<UserStoredValue>().Where(t => t.UserID == takeFoodRecord.UserID).First();
                if (userStoredValue != null)
                {
                    userStoredValue.Value = userStoredValue.Value + takeFoodRecord.Qty * takeFoodRecord.Price;
                    db.Updateable(userStoredValue).ExecuteCommand();

                    //新增取消消费记录
                    UserXpenseTracker userXpenseTracker = new UserXpenseTracker();
                    userXpenseTracker.UserID = takeFoodRecord.UserID;
                    userXpenseTracker.Value = takeFoodRecord.Qty * takeFoodRecord.Price;
                    userXpenseTracker.HallID = takeFoodRecord.HallID;
                    userXpenseTracker.UserValue = userStoredValue.Value;
                    userXpenseTracker.Remark = "取消消费，消费记录ID：" + takeFoodRecord.ID;
                    userXpenseTracker.CreationDate = DateTime.Now;
                    db.Insertable(userXpenseTracker).ExecuteCommand();
                }
                start = dbContext.Delete(takeFoodRecord);
                db.Ado.CommitTran();
            }
            catch (Exception ex)
            {
                db.Ado.RollbackTran();
                logger.Error(ex);
                Console.WriteLine(ex);
                start = false;
            }
            return start;
        }
    }
}
